/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import controllers.DatabaseController;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
import listcontrol.ControlThread;
import listcontrol.CounterThread;
import listcontrol.LocalFileList;
import listcontrol.WatchThread;
import network.FileServer;
import network.ListRequestListener;
import util.IncompleteFile;
import views.MainWindow;



/**
 *
 * @author gravena
 */
public class Main {
    
    public static void main(String args[]) {

        //IncompleteFile.MAX_CONNECTIONS_PER_PEER = Integer.valueOf(args[1]);
        LocalFileList.localUuid = Main.loadUUID();
        Main.loadConfig();
        
        final DatabaseController dbController = new DatabaseController();
                
        new Thread(new FileServer(dbController)).start();
        new Thread(new ControlThread(dbController)).start();        
        new Thread(new CounterThread(dbController)).start();
        new Thread(new ListRequestListener(dbController)).start();
        new Thread(new WatchThread(dbController)).start();
        
                /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainWindow(dbController).setVisible(true);
            }
        });                
        
    }
    
    public static void setBroadcastAddress() {
        try {
            InetAddress local = InetAddress.getLocalHost();
            //Write code to detect broadcast address
        } catch (UnknownHostException ex) {
            System.err.println(ex.getMessage());
        }
    }
    
    public static void loadConfig() {
        File file = new File(".config");
        
        try {
            if(file.exists()) {                
                FileInputStream fis = new FileInputStream(file);
                DataInputStream input = new DataInputStream(fis);                                
                
                IncompleteFile.MAX_CONNECTIONS = input.readInt();
                IncompleteFile.MAX_CONNECTIONS_PER_PEER = input.readInt();
                
                fis.close();
                input.close();                                                
            } else {                                                
                FileOutputStream fos = new FileOutputStream(file);
                DataOutputStream output = new DataOutputStream(fos);
                IncompleteFile.MAX_CONNECTIONS = 50;
                IncompleteFile.MAX_CONNECTIONS_PER_PEER = 1;
                
                output.writeInt(IncompleteFile.MAX_CONNECTIONS);
                output.writeInt(IncompleteFile.MAX_CONNECTIONS_PER_PEER);
                                
                output.close();
                fos.close();
                                
            }
        } catch (IOException ex) {
            System.err.println("AQUI: " + ex.getMessage());
        } 
    }
    
    public static UUID loadUUID() {
        File file = new File(".uuid");
        
        try {
            if(file.exists()) {
                System.out.println("Máquina já possui UUID, lendo do arquivo...");
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream input = new ObjectInputStream(fis);                                
                
                UUID uuid = (UUID)input.readObject();
                
                fis.close();
                input.close();
                
                System.out.println("UUID: " + uuid);
                return uuid;
            } else {
                System.out.println("Máquina não possui UUID, criando e escrevendo no arquivo...");
                UUID random = UUID.randomUUID();
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream output = new ObjectOutputStream(fos);
                output.writeObject(random);
                
                fos.close();
                output.close();
                
                return random;
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        } catch (ClassNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        
        return null;
    }
}
